package com.ocom.payconfig.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.entity.card.EntityXfChannelInfo;
import com.ocom.common.entity.card.EntityXfMerchantInfo;
import com.ocom.common.entity.card.EntityXfSignNo;
import com.ocom.common.entity.company.EntityCompanyInfo;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.entity.master.EntityPayChannel;
import com.ocom.common.entity.payconfig.EntitySignatureRecord;
import com.ocom.common.entity.payconfig.EntityXfSignOrder;
import com.ocom.common.entity.typehandler.PersonInfoHandle;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payconfig.GetUserSignInfoListRequest;
import com.ocom.common.request.payconfig.SignatureListRequest;
import com.ocom.common.request.payconfig.SignatureUpdateRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.PersonVo;
import com.ocom.common.vo.pay.MerchSignVo;
import com.ocom.common.vo.pay.UserSignVo;
import com.ocom.common.vo.payconfig.GetUserSignInfoListVo;
import com.ocom.payconfig.client.HumanClientService;
import com.ocom.payconfig.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2022/7/21
 **/
@Slf4j
@RestController
public class SignController {

    @Autowired
    XfChannelInfoService xfChannelInfoService;

    @Autowired
    PayChannelService payChannelService;

    @Autowired
    XfSignOrderService xfSignOrderService;

    @Autowired
    XfMerchantInfoService xfMerchantInfoService;

    @Autowired
    CompanyInfoService companyInfoService;

    @Autowired
    XfSignNoService xfSignNoService;

    @Autowired
    SignatureRecordService signatureRecordService;

    @Autowired
    PersonnelInfoService personnelInfoService;

    @Autowired
    HumanClientService humanClientService;

    //代扣 列表
    @PostMapping(PayConfigUrl.Url_getSignList)
    public Result list(Long comId, @RequestParam(required = false, defaultValue = "0") Integer payWay) {
        List<EntityXfChannelInfo> list = xfChannelInfoService.getSignChannelList(comId, payWay);

        List<EntityPayChannel> payChannels = payChannelService.payList();
        if (list != null && list.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                EntityXfChannelInfo entityXfChannelInfo = list.get(i);
                for (EntityPayChannel entityPayChannel : payChannels) {
                    if (entityPayChannel.getPayWay().equals(entityXfChannelInfo.getPayWay().toString())) {
                        list.get(i).setPayWayName(entityPayChannel.getName());
                        break;
                    }
                }
            }
        } else {
            list = new ArrayList<>();
        }
        return ResultUtil.success(list);
    }

    //生成代扣申请单
    @PostMapping(PayConfigUrl.Url_addPaySign)
    public Result addPaySign(@RequestBody EntityXfSignOrder entityXfSignOrder) {
        xfSignOrderService.addSignOrder(entityXfSignOrder.getComId(), entityXfSignOrder);
        return ResultUtil.success();
    }

    //更新人员单号测试
    @PostMapping(PayConfigUrl.Url_updatePaySign)
    public Result updatePaySign(@RequestBody EntityXfSignOrder entityXfSignOrder) {
        Boolean b = xfSignOrderService.updateSignOrder(entityXfSignOrder.getComId(), entityXfSignOrder);
        if (!b) {
            return ResultUtil.error(ResultEnum.Err_3014);
        }
        //尝试更新人员信息手机号 如果是建行的
        try {
            if (entityXfSignOrder.getPayWay() == 7 && entityXfSignOrder.getSignType() == 1) {
                EntityXfSignOrder xfSignOrder = xfSignOrderService.getSignOrder(entityXfSignOrder.getComId(), null, entityXfSignOrder.getOrderNo());
                if (xfSignOrder != null && xfSignOrder.getBank()!=null  && xfSignOrder.getBank().length()==11) {
                    EntityPersonnelInfo personnelInfo = personnelInfoService.getOnePersonInfo(xfSignOrder.getComId(),xfSignOrder.getPId());
//                    System.out.println(personnelInfo);
//                    if(CommonUtil.isNull(personnelInfo.getPPhone())){
                        PersonVo personVo=new PersonVo();
                        personVo.setComId(personnelInfo.getComId());
                        personVo.setPId(personnelInfo.getPId());
                        personVo.setPPhone(xfSignOrder.getBank());
                        humanClientService.updatePersonNotCheckPhone(personVo);
//                    }
                }
            }
        } catch (Exception exception) {
            log.error("建行更新人员信息异常 【{}】【{}】",entityXfSignOrder,exception);
        }


        return ResultUtil.success();
    }

    //获取一跳代扣信息
    @PostMapping(PayConfigUrl.Url_getPaySign)
    public Result<EntityXfSignOrder> getPaySign(String outOrderNo) {
        String[] args = outOrderNo.split("A");
        EntityXfSignOrder entityXfSignOrder = xfSignOrderService.getSignOrder(Integer.valueOf(args[0]).longValue(), Integer.valueOf(args[1]), outOrderNo);
        if (entityXfSignOrder != null) {
            return ResultUtil.success(entityXfSignOrder);
        }
        return ResultUtil.error(ResultEnum.Err_3044);
    }


    //获取人员代扣信息
    @PostMapping(PayConfigUrl.Url_getUserSign)
    public Result getUserSign(Long comId, Long pId) {
        //1.商户代扣列表
        List<EntityXfChannelInfo> channelList = xfChannelInfoService.getSignChannelList(comId, 0);
        if (channelList == null) return ResultUtil.success(new ArrayList<>());


        List<EntityXfMerchantInfo> list = xfMerchantInfoService.GetMerchInfo(comId);
        if (list == null) list = new ArrayList<>();

        EntityCompanyInfo entityCompanyInfo = companyInfoService.GetCompanyInfo(comId);
        EntityXfMerchantInfo entityXfMerchantInfo = new EntityXfMerchantInfo();
        entityXfMerchantInfo.setComId(comId);
        entityXfMerchantInfo.setMerchId(0);
        entityXfMerchantInfo.setMerchName(entityCompanyInfo.getComName());
        entityXfMerchantInfo.setMerchOrgin(",");
        entityXfMerchantInfo.setParentMerchId(0);
        entityXfMerchantInfo.setWithholdSubmerch(false);

        //2.所有商户列表 包括单位
        list.add(entityXfMerchantInfo);

        Map<Integer, Boolean> integerBooleanMap = list.stream()
                .collect(Collectors.toMap(EntityXfMerchantInfo::getMerchId, EntityXfMerchantInfo::getWithholdSubmerch));


        List<EntityPayChannel> payChannels = payChannelService.payList();
        Map<Integer, String> stringMap = payChannels.stream()
                .collect(Collectors.toMap(EntityPayChannel::getPayWay, EntityPayChannel::getName));


        //3.用户的代扣列表
        List<EntityXfSignNo> signNos = xfSignNoService.getSignList(comId, pId);

        //4 整合 数据
        List<UserSignVo> userSignVoList = new ArrayList<>();

        for (EntityXfChannelInfo entityXfChannelInfo : channelList) {
            List<Integer> merchList = userSignVoList.stream().map(UserSignVo::getMerchId)
                    .collect(Collectors.toList());

            //自动加签约号  payway  = 30
            if(entityXfChannelInfo.getPayWay()==30){
                MerchSignVo merchSignVo = new MerchSignVo();
                merchSignVo.setPayWay(entityXfChannelInfo.getPayWay());
                if (stringMap.containsKey(entityXfChannelInfo.getPayWay())) {
                    merchSignVo.setPayWayName(stringMap.get(entityXfChannelInfo.getPayWay()));
                }
                merchSignVo.setStatus(1);

                //不存在则添加商户
                if (!merchList.contains(entityXfChannelInfo.getMerchId())) {
                    //添加 商户 和代扣通道
                    UserSignVo userSignVo = new UserSignVo();
                    for (EntityXfMerchantInfo entityXfMerchantInfo1 : list) {
                        if (entityXfMerchantInfo1.getMerchId().equals(entityXfChannelInfo.getMerchId())) {
                            userSignVo.setComId(entityXfMerchantInfo1.getComId());
                            userSignVo.setMerchId(entityXfMerchantInfo1.getMerchId());
                            userSignVo.setMerchName(entityXfMerchantInfo1.getMerchName());
                            List<MerchSignVo> list1 =new ArrayList<>();
                            list1.add(merchSignVo);
                            userSignVo.setPay(list1);
                            break;
                        }
                    }
                    userSignVoList.add(userSignVo);
                }else{
                    for (int i = 0; i < userSignVoList.size(); i++) {
                        UserSignVo userSignVo = userSignVoList.get(i);
                        if (userSignVo.getMerchId().equals(entityXfChannelInfo.getMerchId())) {
                            userSignVo.getPay().add(merchSignVo);
                            userSignVoList.set(i, userSignVo);
                        }
                    }
                }
                continue;
            }

            Boolean flag1 = integerBooleanMap.get(entityXfChannelInfo.getMerchId());
            if (flag1 != null && flag1 == true) {
                continue;
            }

            //不存在则添加商户
            if (!merchList.contains(entityXfChannelInfo.getMerchId())) {
                //添加 商户 和代扣通道
                UserSignVo userSignVo = new UserSignVo();
                for (EntityXfMerchantInfo entityXfMerchantInfo1 : list) {
                    if (entityXfMerchantInfo1.getMerchId().equals(entityXfChannelInfo.getMerchId())) {
                        userSignVo.setComId(entityXfMerchantInfo1.getComId());
                        userSignVo.setMerchId(entityXfMerchantInfo1.getMerchId());
                        userSignVo.setMerchName(entityXfMerchantInfo1.getMerchName());
                        break;
                    }
                }
                userSignVoList.add(userSignVo);
            }

            //添加通道
            MerchSignVo merchSignVo = new MerchSignVo();
            merchSignVo.setPayWay(entityXfChannelInfo.getPayWay());
            if (stringMap.containsKey(entityXfChannelInfo.getPayWay())) {
                merchSignVo.setPayWayName(stringMap.get(entityXfChannelInfo.getPayWay()));
            }
            //判断是否签约
            if (signNos != null) {
                for (EntityXfSignNo signNo : signNos) {
                    if (signNo.getPayWay().equals(entityXfChannelInfo.getPayWay()) &&
                            signNo.getMerchId().equals(entityXfChannelInfo.getMerchId())) {
                        merchSignVo.setStatus(1);
                        break;
                    }
                }
            }
            for (int i = 0; i < userSignVoList.size(); i++) {
                UserSignVo userSignVo = userSignVoList.get(i);
                if (userSignVo.getMerchId().equals(entityXfChannelInfo.getMerchId())) {
                    userSignVo.getPay().add(merchSignVo);
                    userSignVoList.set(i, userSignVo);
                }
            }
        }
        return ResultUtil.success(userSignVoList);
    }


    @PostMapping(PayConfigUrl.Url_getUserPayWay)
    public Result getUserPayWay(Long comId, Long pId, Integer merchId, Integer payWay) {
        EntityXfSignNo entityXfSignNo = xfSignNoService.getUserPayWay(comId, pId, merchId, payWay);
        if (entityXfSignNo == null) return ResultUtil.error(ResultEnum.Err_3044);
        return ResultUtil.success(entityXfSignNo);
    }


    //添加签约
    @PostMapping(PayConfigUrl.Url_addUserSign)
    public Result addUserSign(@RequestBody EntityXfSignNo entityXfSignNo) {
        EntityXfSignNo entityXfSignNo1 = xfSignNoService.getUserPayWay(entityXfSignNo.getComId()
                , entityXfSignNo.getPId()
                , entityXfSignNo.getMerchId()
                , entityXfSignNo.getPayWay()
        );
        if (entityXfSignNo1 != null) {
            return ResultUtil.success();
        }
        Boolean bool = xfSignNoService.addSignNo(entityXfSignNo.getComId(), entityXfSignNo);
        if (!bool) return ResultUtil.error(ResultEnum.Err_3043);
        return ResultUtil.success();
    }

    //删除签约
    @PostMapping(PayConfigUrl.Url_delUserSign)
    public Result delUserSign(@RequestBody EntityXfSignNo entityXfSignNo) {
        Boolean bool = xfSignNoService.delSignNo(entityXfSignNo.getComId(), entityXfSignNo);
        if (!bool) return ResultUtil.error(ResultEnum.Err_3043);
        return ResultUtil.success();
    }

    //获取人员最新一条签约信息 (getUserSignInfo)
    @PostMapping(PayConfigUrl.Url_getUserSignInfo)
    public Result<EntityXfSignNo> getUserSignInfo(@Param("comId") Long comId, @Param("pId")Long pId, @Param("merchId")Integer merchId, @Param("payWay")Integer payWay, @Param("status")Integer status) {
        EntityXfSignNo entityXfSignNo = xfSignNoService.getUserSignInfo(comId, pId, merchId, payWay, status);
        return entityXfSignNo == null ? ResultUtil.error(ResultEnum.Err_3044) : ResultUtil.success(entityXfSignNo);
    }

    //人员签约列表
    @PostMapping(PayConfigUrl.Url_getUserSignInfoList)
    public Result getUserSignInfoList(@RequestBody GetUserSignInfoListRequest request){
        EntityXfSignOrder entityXfSignOrder = Convert.convert(EntityXfSignOrder.class,request);
        List<GetUserSignInfoListVo>  userSignInfoList= this.xfSignOrderService.list(request.getComId(),entityXfSignOrder).stream().map(xfInfo-> Convert.convert(GetUserSignInfoListVo.class,xfInfo)).collect(Collectors.toList());

        List<EntityXfMerchantInfo> list = xfMerchantInfoService.GetMerchInfo(request.getComId());

        userSignInfoList.forEach(sign->{
                    for (EntityXfMerchantInfo entityXfMerchantInfo:list){
                        if (entityXfMerchantInfo.getMerchId().equals(sign.getMerchId())){
                            sign.setMerchName(entityXfMerchantInfo.getMerchName());
                        }
                    }
                });
        return ResultUtil.success(userSignInfoList);
    }

    //添加协议签名信息
    @PostMapping(PayConfigUrl.Url_addSignRecords)
    public Result addSignRecords(@RequestBody EntitySignatureRecord signatureRecord){
        signatureRecord.setStatus(1);
        boolean vb = signatureRecordService.addSign(signatureRecord.getComId(),signatureRecord);
        if(vb){
            return ResultUtil.success();
        }else{
            return ResultUtil.error(ResultEnum.Err_2016);
        }
    }

    //取消协议
    @PostMapping(PayConfigUrl.Url_revokedSignRecords)
    public Result revokedSignRecords(@RequestBody SignatureUpdateRequest request){
        boolean vb = signatureRecordService.revokedSign(request.getComId(),request);
        if(vb){
            return ResultUtil.success();
        }else{
            return ResultUtil.error(ResultEnum.Err_5009);
        }
    }

    //获取列表
    @PostMapping(PayConfigUrl.Url_gzhSignRecords)
    public Result<PageInfo<Map<String, Object>>> gzhSignRecords(@RequestBody SignatureListRequest request){
        PageInfo<Map<String, Object>> list = signatureRecordService.getSignList(request.getComId(),request);
        if(list.getTotal()>0l){
            return ResultUtil.success(list);
        }else{
            return ResultUtil.error(ResultEnum.Err_1001);
        }
    }






    //更新人员单号测试
    @GetMapping("/syncPhone")
    public Result syncPhone(){

        int page = 1;

        Page<EntityXfSignOrder> xfSignOrderPage = xfSignOrderService.list(600l,page,500);


        boolean continueFlag = true ;

        while (continueFlag){
            for (EntityXfSignOrder xfSignOrder: xfSignOrderPage.getRecords()){

                //尝试更新人员信息手机号 如果是建行的
//                try {
                    boolean flag =false;

                    if (xfSignOrder.getPayWay() == 7 && xfSignOrder.getSignType() == 1) {
                        if (xfSignOrder != null && xfSignOrder.getBank()!=null  && xfSignOrder.getBank().length()==11) {
                            EntityPersonnelInfo personnelInfo = personnelInfoService.getOnePersonInfo(xfSignOrder.getComId(),xfSignOrder.getPId());
//                    System.out.println(personnelInfo);
                            if(personnelInfo!=null && CommonUtil.isNull(personnelInfo.getPPhone())){
                                EntityXfSignOrder entityXfSignOrder1 =new EntityXfSignOrder();
                                entityXfSignOrder1.setId(xfSignOrder.getId());
                                entityXfSignOrder1.setSignNo(xfSignOrder.getBank());
                                xfSignOrderService.updatePhone(xfSignOrder.getComId(),entityXfSignOrder1);
                                flag =true ;
                            }
                        }
                    }

                    if(!flag){
                        EntityXfSignOrder entityXfSignOrder1 =new EntityXfSignOrder();
                        entityXfSignOrder1.setId(xfSignOrder.getId());
                        entityXfSignOrder1.setSignNo("123456");
                        xfSignOrderService.updatePhone(xfSignOrder.getComId(),entityXfSignOrder1);
                    }


//                } catch (Exception exception) {
//                    log.error("建行更新人员信息异常 【{}】【{}】",xfSignOrder,exception);
//                }

            }

            page++;
            xfSignOrderPage = xfSignOrderService.list(600l,page,500);

            if(xfSignOrderPage.getRecords().size()==0){
                continueFlag =false;
            }
        }

        return ResultUtil.success();
    }


    //更新人员单号测试
    @GetMapping("/encryPhone")
    public Result encryPhone(){

        int page = 1;

        Page<EntityXfSignOrder> xfSignOrderPage = xfSignOrderService.list(100l,page,500);


        boolean continueFlag = true ;

        while (continueFlag){
            for (EntityXfSignOrder xfSignOrder: xfSignOrderPage.getRecords()){
                if(xfSignOrder.getSignNo()!=null && xfSignOrder.getSignNo().length()==11 ){
                    EntityXfSignOrder entityXfSignOrder1 =new EntityXfSignOrder();
                    entityXfSignOrder1.setId(xfSignOrder.getId());
                    entityXfSignOrder1.setSignNo(PersonInfoHandle.encryptS(xfSignOrder.getBank()));
                    entityXfSignOrder1.setBank(CommonUtil.encryptPhone(xfSignOrder.getBank()));
                    xfSignOrderService.updatePhone(xfSignOrder.getComId(),entityXfSignOrder1);
                }
            }

            page++;
            xfSignOrderPage = xfSignOrderService.list(100l,page,500);

            if(xfSignOrderPage.getRecords().size()==0){
                continueFlag =false;
            }
        }

        return ResultUtil.success();
    }


}
